package com.pai4j.message.factory;

import com.pai4j.message.core.template.TemplateEngine;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 模板引擎工厂
 * 管理和提供TemplateEngine实例
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
public class TemplateEngineFactory {

    /**
     * 引擎映射表
     * key: 引擎名称
     * value: 引擎列表（按优先级排序）
     */
    private static final Map<String, List<TemplateEngine>> ENGINE_MAP = new ConcurrentHashMap<>();

    /**
     * 所有注册的引擎
     */
    private static final Map<String, TemplateEngine> ALL_ENGINES = new ConcurrentHashMap<>();

    /**
     * 默认引擎名称
     */
    private static String defaultEngineName = "simple";

    /**
     * 注册模板引擎
     */
    public static synchronized void register(TemplateEngine engine) {
        if (engine == null) {
            log.warn("尝试注册null TemplateEngine");
            return;
        }

        String name = engine.getName();
        if (name == null || name.trim().isEmpty()) {
            log.warn("TemplateEngine的name不能为空: {}", engine.getClass().getName());
            return;
        }

        String engineId = engine.getClass().getName();
        
        if (ALL_ENGINES.containsKey(engineId)) {
            log.debug("TemplateEngine已注册，跳过: {} for {}", engineId, name);
            return;
        }

        ALL_ENGINES.put(engineId, engine);

        ENGINE_MAP.compute(name.toLowerCase(), (k, engines) -> {
            if (engines == null) {
                engines = new ArrayList<>();
            }
            engines.add(engine);
            engines.sort(Comparator.comparingInt(TemplateEngine::getPriority));
            return engines;
        });

        log.info("注册TemplateEngine成功: {} for {} (priority: {})", 
                engineId, name, engine.getPriority());
    }

    /**
     * 获取指定名称的模板引擎（优先级最高的）
     */
    public static TemplateEngine getEngine(String name) {
        if (name == null || name.trim().isEmpty()) {
            name = defaultEngineName;
        }

        List<TemplateEngine> engines = ENGINE_MAP.get(name.toLowerCase());
        if (engines != null && !engines.isEmpty()) {
            for (TemplateEngine engine : engines) {
                if (engine.isAvailable()) {
                    return engine;
                }
            }
        }

        log.warn("未找到可用的TemplateEngine: name={}", name);
        return null;
    }

    /**
     * 获取默认模板引擎
     */
    public static TemplateEngine getEngine() {
        return getEngine(defaultEngineName);
    }

    /**
     * 获取指定名称的所有模板引擎
     */
    public static List<TemplateEngine> getEngines(String name) {
        if (name == null || name.trim().isEmpty()) {
            return Collections.emptyList();
        }

        List<TemplateEngine> engines = ENGINE_MAP.get(name.toLowerCase());
        return engines != null ? new ArrayList<>(engines) : Collections.emptyList();
    }

    /**
     * 设置默认引擎
     */
    public static void setDefaultEngine(String name) {
        defaultEngineName = name;
        log.info("设置默认模板引擎: {}", name);
    }

    /**
     * 判断是否支持指定引擎
     */
    public static boolean supports(String name) {
        return getEngine(name) != null;
    }

    /**
     * 获取所有已注册的引擎名称
     */
    public static List<String> getAllEngineNames() {
        return ENGINE_MAP.keySet().stream()
                .sorted()
                .collect(Collectors.toList());
    }

    /**
     * 获取所有已注册的引擎
     */
    public static List<TemplateEngine> getAllEngines() {
        return new ArrayList<>(ALL_ENGINES.values());
    }

    /**
     * 取消注册
     */
    public static synchronized void unregister(TemplateEngine engine) {
        if (engine == null) {
            return;
        }

        String engineId = engine.getClass().getName();
        ALL_ENGINES.remove(engineId);

        String name = engine.getName();
        if (name != null) {
            ENGINE_MAP.computeIfPresent(name.toLowerCase(), (k, engines) -> {
                engines.removeIf(e -> e.getClass().getName().equals(engineId));
                return engines.isEmpty() ? null : engines;
            });
            log.info("取消注册TemplateEngine: {} for {}", engineId, name);
        }
    }

    /**
     * 清空所有注册
     */
    public static synchronized void clear() {
        ALL_ENGINES.clear();
        ENGINE_MAP.clear();
        log.info("清空所有TemplateEngine注册");
    }

    /**
     * 获取注册统计信息
     */
    public static String getFactoryInfo() {
        StringBuilder info = new StringBuilder("TemplateEngineFactory Info:\n");
        info.append("Total Engines: ").append(ALL_ENGINES.size()).append("\n");
        info.append("Supported Engine Types: ").append(ENGINE_MAP.size()).append("\n");
        info.append("Default Engine: ").append(defaultEngineName).append("\n");
        for (Map.Entry<String, List<TemplateEngine>> entry : ENGINE_MAP.entrySet()) {
            info.append("  - ").append(entry.getKey()).append(": ")
                .append(entry.getValue().size()).append(" engine(s)\n");
        }
        return info.toString();
    }
}

